package com.wl.android.flutterdemo

import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.idlefish.flutterboost.FlutterBoost
import com.idlefish.flutterboost.FlutterBoostDelegate
import com.idlefish.flutterboost.FlutterBoostRouteOptions
import com.idlefish.flutterboost.FlutterBoostSetupOptions
import com.idlefish.flutterboost.containers.FlutterBoostActivity
import io.flutter.embedding.android.FlutterActivityLaunchConfigs
import io.flutter.embedding.engine.FlutterEngine
import java.io.Serializable


/**
 * @author wangliang at 2021/10/26
 */
object FlutterHelper {

    const val FLUTTER_PAGE_MAIN = "flutter/mainPage"
    const val FLUTTER_PAGE_CALENDAR = "flutter/calendarPage"
    const val FLUTTER_PAGE_TEST = "flutter/testPage"

    const val NATIVE_PAGE_TEST = "native/TestPage"

    fun init(application: Application) {
        FlutterBoost.instance().setup(application, object : FlutterBoostDelegate {
            override fun pushNativeRoute(options: FlutterBoostRouteOptions?) {
                options ?: return

                // 实际项目中优化下
                if (NATIVE_PAGE_TEST == options.pageName()) {
                    val intent = Intent(FlutterBoost.instance().currentActivity(), TestActivity::class.java)
                    val bundle = Bundle().apply { putSerializable("params", options.arguments() as Serializable) }
                    intent.putExtras(bundle)
                    FlutterBoost.instance().currentActivity().startActivityForResult(intent, options.requestCode())
                }
            }

            override fun pushFlutterRoute(options: FlutterBoostRouteOptions?) {
                options ?: return
                Log.d("WLTest", "pushFlutterRoute ${options.pageName()}")
                WLFlutterBoostActivity.launchFlutterPage(options)
            }
        }, { _: FlutterEngine? -> }, FlutterBoostSetupOptions.Builder().isDebugLoggingEnabled(true).build())
    }

    fun getActivityResultData(data: Intent?): Map<String, Any>? {
        return data?.getSerializableExtra("ActivityResult") as? Map<String, Any> ?: null
    }
}